package site.hanzhe.example.jackson.datetime.config;

import cn.hutool.core.date.DatePattern;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

/**
 * JacksonCOnfig
 *
 * @author 张涵哲
 * @since 2024-08-13 11:22:38
 */
@Configuration
public class JacksonConfig {

    @Bean
    public ObjectMapper objectMapper() {
        // 构建ObjectMapper对象
        ObjectMapper objectMapper = new ObjectMapper();
        // 自定义JSON解析配置
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);    // 忽略不存在的属性
        objectMapper.setDateFormat(new SimpleDateFormat(DatePattern.NORM_DATETIME_PATTERN)); // Date类型转换
        // 注册模块
        objectMapper.registerModule(this.getJavaTimeModule());
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        // 将ObjectMapper添加到IOC容器中
        return objectMapper;
    }

    /**
     * 构建Java时间模块，对时间类型JSON解析做处理
     *
     * @author 张涵哲
     * @since 2024-07-25 16:53:33
     */
    private JavaTimeModule getJavaTimeModule() {
        JavaTimeModule module = new JavaTimeModule();
        // LocalTime
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN);
        module.addSerializer(LocalTime.class, new LocalTimeSerializer(timeFormatter));
        // module.addDeserialize r(LocalTime.class, new LocalTimeDeserializer(timeFormatter));
        // LocalDateTime
        DateTimeFormatter datetimeFormatter = DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN);
        module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(datetimeFormatter));
        module.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(datetimeFormatter));
        return module;
    }

}
